package com.ewzj.bigdata.mvp.presenter

import android.app.Application
import android.support.v7.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.ewzj.bigdata.app.config.AppKey
import com.ewzj.bigdata.app.utils.RxUtils
import com.ewzj.bigdata.mvp.contract.VideoFragmentContract
import com.ewzj.bigdata.mvp.model.reqbean.Reqpagebean
import com.ewzj.bigdata.mvp.model.rspbean.VideoBean
import com.ewzj.bigdata.mvp.model.rspbean.VideosData
import com.ewzj.bigdata.mvp.ui.adapter.VideoAdapter
import com.jess.arms.mvp.BasePresenter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import me.jessyan.rxerrorhandler.core.RxErrorHandler
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber
import javax.inject.Inject

/**
 * author:zhangjing
 * 作用:
 * return:
 */
class VideoFragmentPresenter @Inject constructor(val mErrorHandler: RxErrorHandler, val application: Application, view: VideoFragmentContract.View, model: VideoFragmentContract.Model):BasePresenter<VideoFragmentContract.Model,VideoFragmentContract.View>(model,view)
{
    val datas= arrayListOf<VideoBean>()
    val adapter :VideoAdapter by lazy { VideoAdapter(datas) }
    var page=1;
    fun initAdapter(recyclerView: RecyclerView){
        recyclerView.adapter=adapter
        adapter.setOnLoadMoreListener(object :BaseQuickAdapter.RequestLoadMoreListener{
            override fun onLoadMoreRequested() {
                loadmorevideoData()
            }
        },recyclerView)
    }
    fun FirstVidedata(){
        page=1
        mModel.getvideosData(Reqpagebean()).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object :ErrorHandleSubscriber<VideosData>(mErrorHandler){
                    override fun onNext(t: VideosData) {
                        page++
                        adapter.setNewData(t.list)
                        if (t.list.size<AppKey.PAGE_NUM){
                            adapter.disableLoadMoreIfNotFullPage()
                        }
                    }

                })
    }
    fun loadmorevideoData(){
        mModel.getvideosData(Reqpagebean(page)).compose(RxUtils.bindToLifecycle(mRootView))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate { if (adapter.isLoading){
                    adapter.loadMoreComplete()
                } }
                .subscribe(object :Consumer<VideosData>{
                    override fun accept(t: VideosData) {
                       page++
                        if (t.list.size<AppKey.PAGE_NUM){
                            adapter.addData(t.list)
                            adapter.loadMoreEnd()
                        }else{
                            adapter.addData(t.list)
                        }
                    }
                }, Consumer { adapter.loadMoreFail() })
    }

}